package org.zachary.creditbusiness.hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import org.zachary.creditbusiness.hotel.entity.Reservation;
import org.zachary.creditbusiness.hotel.mapper.ReservationMapper;
import org.zachary.creditbusiness.hotel.service.ReservationService;
import org.zachary.creditbusiness.hotel.util.SendReservation;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class ReservationServiceImpl
        extends ServiceImpl<ReservationMapper, Reservation>
        implements ReservationService {

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private SendReservation sendReservation;
    @Override
    public List<Reservation> listByUserId(Integer userId) {
        return list(new QueryWrapper<Reservation>()
                .eq("user_id", userId)
                .orderByDesc("book_date"));
    }

    @Override
    public Reservation repayReservation(Integer orderId) {
        Reservation r = getById(orderId);
        if (r == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "预订记录不存在: " + orderId);
        }
        // 标记已支付
        r.setIsPay(1);
        // 解析 checkoutDate，并与当前时间比较
        LocalDateTime now = LocalDateTime.now();
        String nowStr=now.format(DTF);
        r.setPayDate(nowStr);
        LocalDateTime checkout = LocalDateTime.parse(r.getCheckoutDate(), DTF);
        if (!now.isAfter(checkout)) {
            // 截止日期之前或当天还款，标记 promise=1
            r.setPromise(1);
            updateById(r);
            sendReservation.sendMessage(orderId);
        }else if(r.getPromise()==2){
            updateById(r);
            sendReservation.sendMessage2(orderId);
        }

        return r;
    }

    @Override
    public boolean cancelReservation(Integer orderId) {
        // 直接删除这一条记录
        return this.removeById(orderId);
    }
}